#ifndef SERVER_H
#define SERVER_H

#include "game.h"
#include "player.h"
#include <QObject>
#include <QtNetwork>
#include <QMap>
#include <QTime>


class Server : public QObject
{
   Q_OBJECT
public:
   explicit Server(QObject *parent = 0);
   Server(const QString hostIP, const int hostPort);
   virtual ~Server();
   QTime currentTime();

   void sendMapChange(const QString &filename, QTcpSocket *socket=0);
   void sendEntityUpdates(QTcpSocket *socket=0);
   void sendGameEvents();
   void sendEntityAdd(Entity *entity, QTcpSocket *socket=0);
   void sendEntityRemove(const quint32 id);
   void sendEntitySquadRemove(const quint32 squadID, const quint32 playerID);
   void sendEntitySquadAddToEmitter(const quint32 emitterID, const EntitySquadType &squad);
   void sendEntitySquadRemoveFromEmitter(const quint32 emitterID, const quint32 squadID);
   void sendEntityAttack(const quint32 attackerID, const quint32 targetID, const qint32 damage);

protected:
   void processUserEvent(QDataStream &data);
   void processUserReady(QDataStream &data, quint32 playerID);
   void processEntitySquadIDRequest(QDataStream &data, quint32 playerID);
   void processEntityAdd(QDataStream &data, quint32 playerID);
   void processEntitySquadAdd(QDataStream &data, quint32 playerID);
   void processEntitySquadAddToEmitter(QDataStream &data, quint32 playerID);

   QTcpServer *mTcpServer;
   Game *mGame;
   int mPort;
   int mClientPort;
   quint32 mPlayerIDGen;
   typedef QMap<int, Player *> PlayerMapType;
   PlayerMapType mPlayer;
   QTimer *mTimer;
   quint16 mBlockSize;
   QTime mLastTime;
   QTime mLastNetTime;

public slots:
   void onNewConnection();
   void onDisconnect();
   void onData();
   void onTimer();
};

#endif // SERVER_H
